import { setConfSw2ts } from './config';
import * as Sw2dts from './index';
import logger from './utils/logger';
import {
	readSchemaFromFile, readSchemaFromUrl
} from './utils/request';
const { program } = require('commander');
const sw2ts = require('../package.json');

const GenAPI = (content: any) => {
	if (content) {
		Sw2dts.Generate2API(content);
	} else {
		logger.warn('Logger: 请检查参数或文件是否正确');
	}
};

program.name(sw2ts.name).version(sw2ts.version);
program
	.option('-c, --config <file>', 'set configuration file path')
	.option('-o, --out <file>', 'output filename')
	.option('-d, --dir <path>', 'output dirname')
	.option('-p, --proxy <path>', 'set proxy path', '')
	.option('--url <url>', 'input json schema from the url')
	.option('-r, --required', 'property is required', false)
	.option('-n, --namespace <items...>', 'set namespace separated list', []);

async function command () {
	program.parse(process.argv);
	const options = program.opts();

	if (options.url || program.args.length) {
		setConfSw2ts({
			path: options.dir,
			required: options.required,
			file: options.out,
			proxy: options.proxy,
			namespace: options.namespace
		});

		if (options.url) {
			GenAPI(await readSchemaFromUrl(options.url));
		} else {
			const filename = program.args.shift();
			GenAPI(await readSchemaFromFile(filename));
		}
	} else {
		logger.warn('Logger: 请通过 sw2ts --help，查看必要参数并传入');
	}
}

command().catch((err: Error) => {
	console.error(err.stack ?? err);
});